'''
Author: duliang thinktanker@163.com
Date: 2024-06-04 22:52:54
LastEditors: duliang thinktanker@163.com
LastEditTime: 2024-06-06 21:44:09
FilePath: 
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''

from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.backends import default_backend
from requests import Session


def encrypt_rsa(message, public_key_pem):
    """
    使用RSA公钥对消息进行加密。

    :param message: 要加密的消息（字符串）
    :param public_key_pem: 公钥的PEM格式字符串
    :return: 加密后的数据（字节串）
    """
    public_key = serialization.load_pem_public_key(
        public_key_pem.encode('utf-8'), backend=default_backend())

    # 使用PKCS1v1.5 padding进行加密，这是与JSEncrypt兼容的模式
    ciphertext = public_key.encrypt(
        message.encode('utf-8'),
        padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                     algorithm=hashes.SHA256(),
                     label=None))
    return ciphertext


# 示例使用

public_key_pem = """-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCPlQdq35mgG4pr34ATjI0gWklh3GgsupYTKseAgTI23hWYKUNy2kyUR10Pj/bfG67+iWcPthYWo8mebV5X8EnvCMKGeULVUPCgUJ+eZkBXCvZMPOJT07brIS2+gn1go1vQa31kmT/YWHJ/2XF5tPV2WflmId5C0kty9SGmKTLchQIDAQAB
-----END PUBLIC KEY-----"""

message = "13625252252"
encrypted_message = encrypt_rsa(message, public_key_pem)
userName = encrypted_message.hex()
message = "821101cCW"
encrypted_message = encrypt_rsa(message, public_key_pem)
userPassword = encrypted_message.hex()
loginName = 'NDewp/BgDdmZ1ALPcfrYA9S1NYyVy+VjFFbE3klD4MMoo2A9bR9Cokl0ULlrVarFrbC1gSE+ttL0gBPOji7aYs2d7Q2R9+Qfna/y0XGFMom2q11t4sbEqBq5hyPen9MvSqcosALdGKv2SevEuP78cJo0gkpLwIckhwnOO97t/oE='
passWord = 'f4Zu5slvkK4ZXd34RVHBjogHXSu9BgqAToyrN5Uk68MHywP412N8f30HE68ulw3QvJbQdMF8KLw2FbmWkWxewJmlBo/eILX4jQ9np4fj5YKV3Si4MGN1t92SfoguwI8fILaNpc5UbAu6vIcABOa5rm+6nIZtdf6sJoKga/+pf3I='
session = Session()
url = 'https://www.baomi.org.cn/portal/main-api/loginInNew.do'
login_json = {
    "loginName": loginName,
    "passWord": passWord,
    "deviceId": 1711,
    "deviceOs": "pc",
    "lon": 40,
    "lat": 30,
    "siteId": "95",
    "sinopec": False
}
headers = {
    'Accept': 'application/json, text/plain, */*',
    'User-Agent':
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0',
    'Content-Type': 'application/json;charset=UTF-8',
    # 'token': 'c39cf7fc58a547caaac2145a6a4895cb'
}
response = session.post(url=url,
                        headers=headers,
                        json=login_json,
                        verify=False)
print(response.text)
